package exam;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import javax.imageio.ImageIO;

import org.apache.shiro.util.CollectionUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.ifast.face.domain.UserFaceInfo;
import com.ifast.face.dto.ProcessInfo;
import com.ifast.face.service.FaceEngineService;
import com.ifast.face.service.UserFaceInfoService;
import com.ifast.face.util.ImageInfo;
import com.ifast.face.util.ImageUtil;
import com.ifast.face.util.WorkId;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.io.FileUtil;

import cn.hutool.core.codec.Base64;
import net.coobird.thumbnailator.Thumbnails;
 
/**

 */
public class ImportFaceFile extends TmallApplicationTests {
  
	@Autowired
	UserFaceInfoService userFaceInfoService;
	@Autowired
	FaceEngineService faceEngineService;
    //@Ignore("not ready yet")
    @Test
    public void createExam() throws Exception{ 
    	List<File> files = FileUtil.loopFiles(new File("F:/wiki_crop"));
    	Map<String,List<File>> maps = files.stream().collect(Collectors.groupingBy(File::getParent));
    	 
    	//BufferedImage face  = ImageUtil.read(getClass().getResourceAsStream("/images/standard.jpg"));
    	
//    	for(File file : files){ 
//			System.out.println(file.getAbsolutePath());
//    		//File file = new File("F:/images/1.jpg");
//        	BufferedImage img = ImageUtil.read(file.getAbsolutePath());
//    		userFaceInfoService.saveFace(img,file.getName(),1L,1,10);
//    	while(true){
//    		faceEngineService.findUsersByFaces(face,1L);
//    	}
//        	
//    	} 
    	for(List<File> file : maps.values()){ 
    		serviceScan.execute(new ImportFace(userFaceInfoService,file)); 
    	}
    	serviceScan.shutdown();
    	boolean isFlag=true;
    	while(isFlag){  
            if(serviceScan.isTerminated()){  
            	isFlag = false;
	            System.out.println("所有的子线程都结束了！");  
	            break;  
            }else{
            	System.out.println("--------还未结束-----------------");
            }
            Thread.sleep(10000);    
         }
    }
    public final ExecutorService serviceScan = Executors.newFixedThreadPool(10);  
    
    class ImportFace implements Runnable{
		
    	private UserFaceInfoService userFaceInfoService;//阻塞队列
    	private List<File> files;
    	 
    	public ImportFace(UserFaceInfoService userFaceInfoService,List<File> files){
    		this.userFaceInfoService = userFaceInfoService;
    		this.files = files; 
    	}
    	
    	@Override
    	public void run(){
    		try {
    			for(File file : files){  
    				System.out.println(file.getAbsolutePath()); 
    				UserFaceInfo user = file2Base64(file,UserFaceInfo.builder().build());
    				if(user.getFaceFeature() == null){
    					continue;
    				}
    				user.setName(file.getName())
    					.setAge(10)
    					.setGender(0) 
    					.setGroupId(1L)
    					.setChecked(0)
    					.setCreateTime(DateUtil.now())
    					.setFaceId(WorkId.sortUID());
    				userFaceInfoService.save(user); 
    	    	} 
    		} catch (Exception e){ 
    			e.printStackTrace();
    		} 
    	}
    	private UserFaceInfo file2Base64(File file,UserFaceInfo user){
    		try(InputStream inputStream = new FileInputStream(file);
    				ByteArrayOutputStream stream2 = new ByteArrayOutputStream();){
    			
    	        BufferedImage bufImage = ImageIO.read(inputStream);
    	        ImageInfo imageInfo = ImageUtil.bufferedImage2ImageInfo(bufImage); 
    	        //人脸特征获取
    	        List<ProcessInfo> process = faceEngineService.extractFaceFeature(imageInfo);  
    	        if (CollectionUtils.isEmpty(process)) {
    	        	return user;
    	        } 
    	        byte[] bytes = process.get(0).getFaceFeature().getFeatureData();
    	        user.setFaceFeature(bytes);
    	        Thumbnails.of(bufImage).scale(0.5).outputFormat("jpg").toOutputStream(stream2);
    			user.setImgPath("data:image/jpeg;base64,"+Base64.encode(stream2.toByteArray())); 
    		} catch (Exception e) {
    			 e.printStackTrace();
    		}
    		return user;
    	} 
    }
    
}